<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>

                    <div class="row">
                        <div class="col-sm-12">
                             <div class="box">
                                <div class="box-header with-border">
                                <h2 class="page-header">
                                    <i class="fa fa-globe"></i> <?php echo $site["name"];?> 网站产品
                                    <small class="pull-right"> <a href="<?php echo $site["domian"];?>" target="_blank"><?php echo $site["domian"];?></a></small>

                                </h2>

                                <?php echo $nav;?>

                                </div>
                                <div class="box-body">
                                
                                <div class="row">
                                    <div class="col-sm-6">
                                        <input type="button" class="btn btn-sm btn-danger btn-flat" value="批量删除" id="batchdel">
                                        <!--
                                        <input type="button" class="btn btn-sm bg-olive btn-flat" value="批量推送SHOPPING" id="batchtag">
                                        <input type="button" class="btn btn-sm btn-success btn-flat" value="推送所有SHOPPING" id="batchtag">
                                        <input type="button" class="btn btn-sm btn-warning btn-flat" value="同步SHOPPING状态" id="batchpush">
                                        -->
                                    </div>
                                    <div class="pull-right" style="margin-right:15px;">
                                    
                                    <?php echo form_open(current_url(), array('class' => 'form-inline', 'method'=>'get', 'id' => 'search_goods')); ?>                                    
                                    
                                    <div class="form-group" style="margin-right:15px;">
                                    <?php echo form_input($keyword);?>
                                    </div>
                                    <!--
                                    <input type="number" name="min" value="" id="min" class="form-control input-sm" placeholder="最低价" maxlength="10" style="width:90px;">
                                    -
                                    <input type="number" name="max" value="" id="max" class="form-control input-sm" placeholder="最高价" maxlength="10" style="width:90px;">
                                    -->

                                    <?php echo form_button(array('type' => 'submit', 'class' => 'btn btn-sm btn-primary btn-flat', 'content' => "搜索产品")); ?>
                                    
                                    
                                    <?php echo form_close();?>
                                    

                                    </div>

                                </div>
                             

                                <?php if($loglist):?>

                                <?php echo form_open(current_url(), array('class' => 'form-inline', 'method'=>'post', 'id' => 'batch_goods')); ?>                                   
                                    <table class="table table-striped table-hover" style="margin-top:20px;">
                                        <thead>
                                            <tr>
                                                <th>名称</th>
                                                <!--<th>价格</th>-->
                                                <!--<th>销量</th>-->
                                                <!--<th>SHOPPING</th>-->
                                                <th width="240">管理</th>
                                            </tr>
                                        </thead>
                                        <tbody>
<?php foreach ($loglist as $item):?>
<tr shopid="<?php echo $item["id"]; ?>">
    <td ondblclick="edit(this,'title')"><?php echo $item["title"]; ?></td>

    
    <!--
    <td><?php echo $item["sellcount"];?></td> -->
    <!--<td><?php echo $item["gshopon"]==1?'<i class="fa fa-fw fa-check-square text-green"></i>':'<i class="fa fa-fw fa-minus-square text-red"></i>';?></td>
    -->
    <td>
    <a href="<?php echo getproeditlink($site,$item["rid"]);?>" target="_blank" class="btn btn-xs btn-flat btn-info">产品编辑</a>
    <?php if($site["sitetype"]==2){?>
    <a href="<?php echo getpropriceeditlink($site,$item["title"]);?>" target="_blank" class="btn btn-xs btn-flat btn-info">价格编辑</a>
    <?php }?>

    <a href="<?php echo isset($sourceurl[$item["productid"]])?$sourceurl[$item["productid"]]:"https://www.google.com/search?q=".$item["title"];?>" class="btn btn-xs btn-flat btn-success" target="_blank">来</a>
    <a href="/backend/products/editgoods/<?php echo $item["productid"];?>" class="btn btn-xs btn-flat btn-info">源</a>
    <?php
    if($item["url"]):
        if(substr($item["url"],0,4)!="http")
        {
            $item["url"]=$site["domian"].$item["url"];
        }
    ?>
    <a href="<?php echo $item["url"];?>" class="btn btn-xs btn-flat btn-primary" target="_blank">站</a>
    <?php
    endif;
    ?>
    <button class="btn btn-xs btn-flat btn-danger btn-delete" itemid="<?php echo $item["id"];?>">删除</button>
    </td>
</tr>

<?php endforeach;?>
                                        </tbody>
                                    </table>

                                    <?php echo form_close();?>

                                    <?php endif;?>
                                    <?php 
                                    if(empty($loglist)){
                                        echo "<h2 style='text-align:center;padding:50px 0;'>没有查询到数据</h2>";
                                    }
                                    ?>

<?php echo $pager;?>

<div class=" pull-right form-inline" style="line-height:30px;margin-top:25px;">
    <?php echo '共'.$total.'条产品，'.$page.'/'.$pages.'页';?> 

    <select id="pagesize" class="form-control input-sm" style="height:22px;">
        <option value="0">每页数量</option>
        <option value="50">50</option>
        <option value="100">100</option>
        <option value="200">200</option>
        <option value="500">500</option>
    </select>
   
    <input type="text" id="topage" value="" class="form-control input-sm" placeholder='页码' style="margin:0 5px;height:22px;width:45px;"> 
    <?php echo form_button(array('type' => 'submit', 'class' => 'btn btn-xs btn-primary btn-flat', 'id'=>'jumpbtn','content' => "跳转")); ?>
</div>

                                </div>
                            </div>
                         </div>
                    </div>
        


       
<script>



window.addEventListener('DOMContentLoaded', function() {
	(function($) {
		$(document).ready(function() {

		

			// Init iCheck
			
			var elem_input = $('input');
 			if (elem_input.length) {
				elem_input.iCheck({
					checkboxClass: 'icheckbox_square-blue',
					radioClass   : 'iradio_square-blue'
				});
			}
		
		});

	
	})(jQuery);
});


$(function(){

function initTableCheckbox() {
    var $thr = $('table thead tr');
    var $checkAllTh = $('<th><input type="checkbox" id="checkAll" name="checkAll" /></th>');
    $thr.prepend($checkAllTh);
    $('#checkAll').on('ifChecked ifUnchecked', function(event){
        $tbr.find('input').each(function(){
            $(this).iCheck('toggle');
            $(this).parent().parent().toggleClass('warning');
        });
    });     
    var $tbr = $('table tbody tr');
    var $checkItemTd = $('<td><input type="checkbox" name="checkItem[]" /></td>');
    $tbr.prepend($checkItemTd);

    $tbr.find('input').on('ifChecked ifUnchecked',function(event){
        $(this).val($(this).parent().parent().parent().attr("shopid"));
        $(this).parent().parent().parent().toggleClass('warning');
    });
    $tbr.click(function(){
       $(this).find('input').iCheck('toggle');
    });
}
initTableCheckbox();

    $("#batchdel").on("click",function(){

        var checkcount=0;
        var delids=[];
        $("table tbody").find("input").each(function(){if($(this).prop('checked')){checkcount=checkcount+1;delids.push($(this).val());}});
        if(checkcount==0){layer.alert('没有选中任何数据'); return;}
        console.log(delids);

        layer.open({
            type: 1,
            skin: 'layui-layer-molv', //样式类名
            closeBtn: 0, //不显示关闭按钮
            anim: 2,
            shadeClose: false, //开启遮罩关闭
            content: "<div style='padding:20px 20px;' id='tipmsg'>共有"+delids.length+"条产品等待删除,请勿关闭窗口</div>"
        });

        function delproduct(delids)
        {
            let defer = $.Deferred();
            let dcount = 0;
            $.each(delids, function(index,val) {
                
                $.ajax({
                    url: "/backend/sites/product/ajaxdel",
                    type: "post",
                    data: {"cid":val},
                    dataType:"json",
                    success:function(result){
                        dcount = dcount + 1;
                        if(result.status==0)
                        {
                            layer.msg(result.msg);
                        }
                        else
                        {
                            $("#tipmsg").text('已经删除产品 '+dcount+'/'+delids.length+',请勿关闭窗口');
                        }
                        if(delids.length==dcount){
                            defer.resolve();
                        }
                    }      
                });
                
            }); 
            return defer;
        }

        delproduct(delids).then(function(){
            layer.closeAll();
            layer.msg("删除成功");
            setTimeout(() => {
                location.href=location.href;
            }, 2000);
        });
    });
});

    var atedit=0;
    var sitetype=<?php echo $site["sitetype"];?>;
    var siteid=<?php echo $site["id"];?>;

    function edit(obj,attrName){

        if(atedit==1)
        {
            return;
        }
        else
        {
            atedit=1;
        }
        var oldHtml = obj.innerHTML;
        var newobj = document.createElement('input');
        newobj.name = attrName;
        newobj.type = "text";
        newobj.setAttribute("class","form-control input-sm");
        newobj.value = oldHtml;
        var cid = $(obj).parent().attr("shopid");     
        obj.innerHTML = '';  
        obj.appendChild(newobj);
        newobj.focus(); 

        $(newobj).keydown(function (event) {
            if (event.keyCode == 13) {
                $(this).trigger("blur");
            }
        });

        $(newobj).blur(function(){
            atedit=0;
            if(this.value==null || this.value==""){
                obj.innerHTML = oldHtml;
                return false;
            }
            obj.innerHTML = this.value?this.value:oldHtml;       
            if(oldHtml != this.value){
                /*
                if(sitetype==2 && attrName=="price")
                {
                    newvalue=this.value;

                    layer.prompt({
                        formType: 0,
                        placeholder: '补充市场价',
                        title: '请输入市场价',
                        btn2: function() {
                            obj.innerHTML = oldHtml;
                        },
                    }, function(value, index, elem){
                        layer.close(index);
                        $.ajax({
                            type:"post",
                            url:"/backend/sites/product/ajaxedit",
                            dataType:"json",
                            data:{"attrName":attrName,"comprice":value,"newHtml":newvalue,"cid":cid},
                            error:function(){
                            },
                            success:function(result){
                                if(result["status"]!=1)
                                {
                                    layer.msg(result["msg"]);                                    
                                }
                            },
                        });
                    });
                }
                else
                {
                */

                    $.ajax({
                        type:"post",
                        url:"/backend/sites/product/ajaxedit",
                        dataType:"json",
                        data:{"attrName":attrName,"newHtml":this.value,"cid":cid},
                        error:function(){
                        },
                        success:function(result){
                            if(result["status"]!=1)
                            {
                                layer.msg(result["msg"]);
                            }
                        },
                    });

                /*

                }
                */

               
                
            }  

        })
    }

    $("span.btn-opprice2").on("click",function(){
        let rid=$(this).attr("rid");
        let title=$(this).attr("title");
        let itemid=$(this).attr("itemid");
        let oldprice=$(this).attr("oldprice");
        $.getJSON("/backend/sites/product/querysubprice2/"+itemid,function(result){
            if(result["status"]==1)
            {
                if(result["opprice"].length>0)
                {
                    $.each(result["opprice"], function(i, item){
                        $("div#allop").append('<div class="form-group"><input type="hidden" name="opid[]" value="'+item["opid"]+'"><label class="opt">'+item["opname"]+'</label> <input type="text" name="opprice[]" value="'+item["opval"]+'" placeholder="请输入变体价格,不填价格不变" class="form-control input-sm "></div>');
                    });
                }
                else
                {
                    $("div#allop").append('<div class="form-group"><input type="text" name="allprice" value="'+oldprice+'" placeholder="请输入所有产品价格，不填价格不变" class="form-control input-sm "></div>')
                }
            }
        });
        layer.open({
            type: 1,
            title: '请设置变体价格',
            closeBtn: 1,
            offset : '100px',
            shadeClose: true,
            skin: 'layui-layer-lan',
            content: '<div style="padding:20px 30px;"><h4>'+title+'</h4><div class="layui-layer-content" style="margin-bottom:10px;height:500px;overflow-y:scroll;" id="allop"><div class="form-group"><button rid="'+rid+'" cid="'+itemid+'" id="submitopprice2" class="btn btn-flat btn-info">同步变体价格</button> <span class="btn btn-flat btn-primary batchbtn">批</span></div></div></div>'
        });
        return false;
    });

    $("body").on("click","span.batchbtn",function(){
        var setprice = $("input[name^='opprice']:eq(0)").val();
        $("input[name^='opprice']").val(setprice);
        layer.msg("批量设置成功");
    });

    $("span.btn-opprice").on("click",function(){
        let opval=$(this).attr("option").split(",");
        let rid=$(this).attr("rid");
        let title=$(this).attr("title");
        let itemid=$(this).attr("itemid");
        $.getJSON("/backend/sites/product/querysubprice/"+itemid,function(result){
            if(result["status"]==1)
            {
                $.each(result["opprice"], function(i, item){
                    $("label.opt:eq("+i+")").text($("label.opt:eq("+i+")").text()+' : '+item);
                });
            }
        });

        let ophtml="";
        $.each(opval, function(i, item){     
            ophtml+='<div class="form-group"><input type="hidden" name="opname[]" value="'+item+'"><label class="opt">'+item+'</label> <input type="text" name="opprice[]" placeholder="请输入变体价格,不填价格不变" class="form-control input-sm "></div>';
        });
        layer.open({
            type: 1,
            title: '请设置变体价格',
            closeBtn: 1,
            offset : '100px',
            shadeClose: true,
            skin: 'layui-layer-lan',
            content: '<div style="padding:20px 30px;"><h4>'+title+'</h4><div class="layui-layer-content" style="margin-bottom:10px;">'+ophtml+'<div class="form-group"><button rid="'+rid+'" id="submitopprice" class="btn btn-flat btn-info">同步变体价格</button></div></div></div>'
        });
        return false;
    });


    $("body").on("click","button#submitopprice2",function(){
        let opprice=[];
        let opid=[];
        let rid=$(this).attr("rid");
        let checkprice = 0;
        if($("input[name^='opprice']").length==0)
        {
            let newprice = parseFloat($("input[name=allprice]").val());
            let cid=$(this).attr("cid");
            shadow = layer.load(1, {
                shade: [0.1,'#000'] 
            });
            $.ajax({
                type:"post",
                url:"/backend/sites/product/ajaxedit",
                dataType:"json",
                data:{"attrName":"price","newHtml":newprice,"cid":cid},
                error:function(){
                },
                success:function(result){
                    if(result["status"]!=1)
                    {
                        layer.msg(result["msg"]);                                    
                    }
                    else
                    {
                        layer.closeAll();
                        layer.msg("价格修改成功");      
                        $("tr[shopid="+cid+"]").find("span.price").text(newprice);
                    }
                },
            });
            return;
        }

        $("input[name^='opprice']").each(function(i, el) {
            if($(this).val().length==0)
            {
                price=0;
            }
            else
            {
                price=parseFloat($(this).val());
            }
            if(isNaN(price))
            {
                checkprice=1;
            }           
            opprice.push(price);
        });
        $("input[name^='opid']").each(function(i, el) {
            opid.push($(this).val());
        });
        let pushdata={
            "rid":rid,
            "opprice":opprice,
            "siteid":siteid,
            "opid":opid
        };
        if(checkprice==1)
        {
            layer.msg("价格必须为数字");
        }
        else
        {
            shadow = layer.load(1, {
                shade: [0.1,'#000'] 
            });
            $.ajax({
                type:"post",
                url:"/backend/sites/product/subopprice2",
                dataType:"json",
                data:pushdata,
                error:function(){
                    layer.closeAll();
                    layer.msg("系统错误,请联系管理员");                   
                },
                success:function(data){
                    layer.closeAll();
                    if(data.status==1)
                    {
                        layer.msg("价格同步成功");
                    }
                    else
                    {
                        layer.msg(data.msg);
                    }
                },
            });
            console.log(pushdata);
        }
    });


    $("body").on("click","button#submitopprice",function(){
        let opname=[];
        let opprice=[];
        let rid=$(this).attr("rid");
        let checkprice = 0;
        $("input[name^='opprice']").each(function(i, el) {
            if($(this).val().length==0)
            {
                price=0;
            }
            else
            {
                price=parseFloat($(this).val());
            }
            if(isNaN(price))
            {
                checkprice=1;
            }
            opprice.push(price);
        });
        $("input[name^='opname']").each(function(i, el) {
            opname.push($(this).val());
        });
        let pushdata={
            "rid":rid,
            "siteid":siteid,
            "opname":opname,
            "opprice":opprice,
        };
        if(checkprice==1)
        {
            layer.msg("价格必须为数字");
        }
        else
        {
            shadow = layer.load(1, {
                shade: [0.1,'#000'] 
            });
            $.ajax({
                type:"post",
                url:"/backend/sites/product/subopprice",
                dataType:"json",
                data:pushdata,
                error:function(){
                    layer.closeAll();
                    layer.msg("系统错误,请联系管理员");                   
                },
                success:function(data){
                    layer.closeAll();
                    if(data.status==1)
                    {
                        layer.msg("价格同步成功");
                    }
                    else
                    {
                        layer.msg(data.msg);
                    }
                },
            });
            console.log(pushdata);
        }
    });

    $("button.btn-delete").on("click",function(event){
        event.preventDefault();
        var cid=$(this).attr("itemid");
        var row=$(this).parent().parent();
        layer.confirm("确认要删除吗，网站数据也会被删除，删除将无法恢复？", { title: "确认" }, function (index) {           
            
            shadow = layer.load(1, {
                shade: [0.1,'#000'] 
            });
            $.ajax({
                type:"post",
                url:"/backend/sites/product/ajaxdel",
                dataType:"json",
                data:{"cid":cid},
                error:function(){
                    layer.close(shadow);
                },
                success:function(result){
                    if(result["status"]==1)
                    {
                        row.remove();
                    }
                    else
                    {
                        layer.msg(result["msg"]);
                    }
                    layer.close(shadow);
                },
            });
            layer.close(index); 
        });
    });


    $("select#pagesize").change(function(){
        pagesize=$("select#pagesize option:selected").val();
        if(pagesize>0)
        {
            var url= window.location.href;
            var newUrl=  changeURLArg(url, "pagesize", pagesize); 
            window.location.href =  newUrl;
        }
    });


    function changeURLArg(url, arg, arg_val) {
        var pattern = arg + '=([^&]*)';
        var replaceText = arg + '=' + arg_val;
        if (url.match(pattern)) {
            var tmp = '/(' + arg + '=)([^&]*)/gi';
            tmp = url.replace(eval(tmp), replaceText);
            return tmp;
        } else {
            if (url.match('[\?]')) {
                return url + '&' + replaceText;
            } else {
                return url + '?' + replaceText;
            }
        }
        return url + '\n' + arg + '\n' + arg_val;
    }
</script>
